//
//  WZHCountDownOperation.swift
//  ShiGuangJiaSwift
//
//  Created by point on 2022/8/18.
//

import Foundation
import UIKit
public class WZHCountDownQueue: OperationQueue {
    //单例
    public static let shared = WZHCountDownQueue()
    private override init() {
        super.init()
        self.maxConcurrentOperationCount = 3;//最多允许3条线程
    }
}


public class WZHCountDownOperation: Operation {
    /** 正在倒计时时，每秒钟会回调一次，将当前秒数返回 */
    public var countDowning : ((_ timeInterval : TimeInterval)->())?
    /** 倒计时完成后的回到，将当前秒数返回（永远为0，因为已经倒计时完了） */
    public var countDownFinished : ((_ timeInterval : TimeInterval)->())?
    /** 后台任务标示,确保任务进入后台依然能够计时 */
    public var taskIdentifier : UIBackgroundTaskIdentifier?
    /** 当前操作的剩余时间 */
    public var leftTime : TimeInterval = 0
    /** 当前操作的剩余时间字符串 */
    public var leftTimeStr : String?
    
    
    public override func main(){
        self.taskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
        
        let time = Int(leftTime)
        
        for index in 0..<time {
            leftTime -= 1
            
            DispatchQueue.global(qos: .background).async {
                DispatchQueue.main.async {[weak self] in
                    self?.countDowning?(TimeInterval(time - index))
                }
            }
            
            /* 睡眠一秒钟 */
            sleep(1);
        }
            
        DispatchQueue.global(qos: .background).async {
            DispatchQueue.main.async {[weak self] in
                self?.countDownFinished?(0)
            }
        }
        
        if (self.taskIdentifier != .invalid) {
            UIApplication.shared.endBackgroundTask(self.taskIdentifier!)
            self.taskIdentifier =  .invalid;
        }
    }
}
